package com.xbongbong.paas.help.subform;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.saas.domain.entity.PurchaseUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.enums.subform.PurchaseTeamEnum;
import com.xbongbong.paas.help.subform.abstracts.AbstractUserTeamTransferSubForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 采购合同 es和数据库格式转化
 * @author 魏荣杰
 * @date 2020/8/24 10:06
 * @since
 * @version
 */
@Component
public class PurchaseTeamTransferSubForm extends AbstractUserTeamTransferSubForm {

    private static final Logger LOG = LoggerFactory.getLogger(PurchaseTeamTransferSubForm.class);

    @Override
    public PaasFormDataEntity transferTeamToFormData(UserTeamEntity userTeamEntity) {
        PurchaseUserEntity purchaseUserEntity = (PurchaseUserEntity) userTeamEntity;
        PaasFormDataEntity paasFormDataEntity = createPaasFormDataEntityForUserTeam(userTeamEntity);

        JSONObject teamJson = JSONObject.parseObject(JSON.toJSONString(purchaseUserEntity));

        JSONObject data = new JSONObject();

        PurchaseTeamEnum[] purchaseTeamEnums = PurchaseTeamEnum.values();
        for (PurchaseTeamEnum purchaseTeamEnum : purchaseTeamEnums) {
            String dbAttr = purchaseTeamEnum.getDbAttr();
            String dataAttr = purchaseTeamEnum.getDataAttr();
            Integer fieldType = purchaseTeamEnum.getFieldType();
            formatDataForEs(teamJson, data, dbAttr, dataAttr, fieldType);
        }
        paasFormDataEntity.setData(data);

        return paasFormDataEntity;
    }

    @Override
    public UserTeamEntity transferFormDataToTeam(PaasFormDataEntity paasFormDataEntity) {
        JSONObject data = paasFormDataEntity.getData();

        JSONObject dbData = new JSONObject();
        PurchaseTeamEnum[] purchaseTeamEnums = PurchaseTeamEnum.values();
        for (PurchaseTeamEnum purchaseTeamEnum : purchaseTeamEnums) {
            String dbAttr = purchaseTeamEnum.getDbAttr();
            String dataAttr = purchaseTeamEnum.getDataAttr();
            Integer fieldType = purchaseTeamEnum.getFieldType();
            formatDataForDb(data, dbData, dbAttr, dataAttr, fieldType);

        }
        PurchaseUserEntity purchaseUserEntity = JSON.parseObject(dbData.toJSONString(), PurchaseUserEntity.class);
        purchaseUserEntity.setAddTime(paasFormDataEntity.getAddTime());
        purchaseUserEntity.setUpdateTime(paasFormDataEntity.getUpdateTime());
        purchaseUserEntity.setCorpid(paasFormDataEntity.getCorpid());
        purchaseUserEntity.setDel(paasFormDataEntity.getDel());
        purchaseUserEntity.setId(paasFormDataEntity.getId());

        return purchaseUserEntity;
    }
}
